/**
 * Copyright (C) 2013 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Mobile Communication Division,
 * Digital Media & Communications Business, Samsung Electronics Co., Ltd.
 *
 * This software and its documentation are confidential and proprietary
 * information of Samsung Electronics Co., Ltd.  No part of the software and
 * documents may be copied, reproduced, transmitted, translated, or reduced to
 * any electronic medium or machine-readable form without the prior written
 * consent of Samsung Electronics.
 *
 * Samsung Electronics makes no representations with respect to the contents,
 * and assumes no responsibility for any errors that might appear in the
 * software and documents. This publication and the contents hereof are subject
 * to change without notice.
 */

package sharevideo;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.Inflater;


import sharevideo.NodeListAdapter.IFileCancelListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.minimusicdemo.SongUtility;
import com.example.project22_editingmediaplayer.MainActivity;
import com.example.project22_editingmediaplayer.R;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.chord.InvalidInterfaceException;
import com.samsung.android.sdk.chord.Schord;
import com.samsung.android.sdk.chord.SchordChannel;
import com.samsung.android.sdk.chord.SchordManager;
import com.samsung.android.sdk.chord.SchordManager.NetworkListener;

public class ShareVideo extends Activity implements IFileCancelListener {
	SchordChannel channel1;
	String trId = null;
	String toNode = null;
	Button btpause;
	int i=0;
	AlertDialog dialog;
	String Path;
	static TextView tv_current;
	static TextView tv_total;
	ImageButton bt_toward,bt_backward,bt_playpause;
	static SeekBar seckbarprogress;
	static Handler handler=new Handler();
	private static SongUtility utils1;
	boolean isshared=false,isappearcontrol=false;
	View viewcontrolplayer,viewtotal;
	
	
	private static final String CHORD_SAMPLE_MESSAGE_TYPE = "com.samsung.android.sdk.chord.example.MESSAGE_TYPE";

	static VideoView videoView;
	MediaController mediaController;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.send_files_fragment);
		
		Path=getIntent().getExtras().getString("key");
	
		tv_current=(TextView)findViewById(R.id.tv_current);
		tv_total=(TextView)findViewById(R.id.tv_total12);
	
		bt_playpause=(ImageButton)findViewById(R.id.bt_playpause);
		seckbarprogress=(SeekBar)findViewById(R.id.seeckbarprogress);

        viewcontrolplayer=(View)findViewById(R.id.controlvideo);
        viewtotal=(View)findViewById(R.id.viewtotal);
		utils1=new SongUtility();
		
		
		Thread background = new Thread (new Runnable() 
	    {
	       public void run() 
	        {
	            try
	            {
	                Thread.sleep(4000);
	                progressHandler.sendMessage(progressHandler.obtainMessage());

	            } 
	            catch (InterruptedException e)
	            {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	       }
	    });

	    // start the background thread
	    background.start();
		
		
		seckbarprogress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				handler.removeCallbacks(updateprogres);
				int totalDuration = videoView
						.getDuration();
				int currentPosition = utils1.progressToTimer(seckbarprogress.getProgress(),
						totalDuration);
				videoView.seekTo(currentPosition);
				updateProgressBar1();
				if (isshared) {
					
					for (int i = 0; i < mNodeListAdapter.getCheckedNodeList().size(); i++){
					byte[][] payload = new byte[1][];
		            payload[0] = (""+currentPosition).getBytes();
				toNode = mNodeListAdapter.getCheckedNodeList().get(i);
				SchordChannel channel = mChordManager.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
	            channel.sendData(toNode, "currentpositionpg", payload);
				}
				}
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				handler.removeCallbacks(updateprogres);
			}
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				
			}
		});
		videoView=(VideoView)findViewById(R.id.videoView1);
		mNodeListAdapter = new NodeListAdapter(ShareVideo.this
				.getApplicationContext(), this);
		if(!(Path.equals("share"))){
			mediaController=new MediaController(this);
		
			videoView.setVideoPath(Path);
	        videoView.setMediaController(null)  ;
	        videoView.requestFocus();
	        videoView.start();
	        viewtotal.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (isappearcontrol) {
						viewcontrolplayer.setVisibility(View.GONE);
						isappearcontrol=false;
					}else {
						viewcontrolplayer.setVisibility(View.VISIBLE);
						isappearcontrol=true;
					}
					
				}
			});
	       videoView.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				videoView.setVideoPath(Path);
				videoView.start();
				seckbarprogress.setMax(100);
				updateProgressBar1();
			}
		});
			
	   
		
	       bt_playpause.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(videoView.isPlaying()){
					bt_playpause.setImageResource(R.drawable.apollo_holo_light_play);
					
					videoView.pause();
					if (isshared) {
						
						for (int i = 0; i < mNodeListAdapter.getCheckedNodeList().size(); i++){
						byte[][] payload = new byte[1][];
			            payload[0] = "pause".getBytes();
					toNode = mNodeListAdapter.getCheckedNodeList().get(i);
					SchordChannel channel = mChordManager.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
		            channel.sendData(toNode, "playpause", payload);
					}
					}
					
					
				}else{
					
					videoView.start();
					if (isshared) {
						for (int i = 0; i < mNodeListAdapter.getCheckedNodeList().size(); i++){
						byte[][] payload = new byte[1][];
			            payload[0] = "play".getBytes();
					toNode = mNodeListAdapter.getCheckedNodeList().get(0);
					SchordChannel channel = mChordManager.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
		            channel.sendData(toNode, "playpause", payload);
					}
					
					}
	            bt_playpause.setImageResource(R.drawable.apollo_holo_light_pause);
				}
				
			}
		});
	       
	       
		}else{
			
			viewcontrolplayer.setVisibility(View.GONE);
			isshared=true;
		}
	
		 seckbarprogress.setMax(100);
			updateProgressBar1();
		mAlertDialogMap = new HashMap<String, AlertDialog>();
		

		
	
	}
	
	// handler for the background updating
	Handler progressHandler = new Handler() 
	{
	    public void handleMessage(Message msg) 
	    {
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    }
	};
	
	
	public static void updateProgressBar1() {
		handler.postDelayed(updateprogres, 100);
	}
	static Runnable updateprogres =new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
		
				long totalDuration = videoView.getDuration();
				long currentDuration = videoView.getCurrentPosition();
						

				// Displaying Total Duration time
				tv_total.setText(""
						+ utils1.milliSecondsToTimer(totalDuration));
				// Displaying time completed playing
				tv_current.setText(""
						+ utils1.milliSecondsToTimer(currentDuration));

				// Updating progress bar
				int progress = (int) (utils1.getProgressPercentage(
						currentDuration, totalDuration));
				seckbarprogress.setProgress(progress);
				handler.postDelayed(this, 100);
			}
			
	
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.menushare, menu);
		return super.onCreateOptionsMenu(menu);
		
		
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.sharevideo:
			
		    LayoutInflater li = LayoutInflater.from(ShareVideo.this);
		    View view= li.inflate(R.layout.dialogshare, null);
		    dialog = new AlertDialog.Builder(ShareVideo.this).create();
		    dialog.setView(view);
		    Button buttonok=(Button)view.findViewById(R.id.btokshare);
		    Button buttoncancel=(Button)view.findViewById(R.id.btcancelshare);
		    mNode_listView=(ExpandableListView)view.findViewById(R.id.node_listView1);
			//if(mNodeListAdapter!=null){
		    mNode_listView.setAdapter(mNodeListAdapter);
		    
			buttoncancel.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					
				}
			});
			buttonok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub


					if (mNodeListAdapter.getCheckedNodeList().isEmpty()) {
						Toast.makeText(ShareVideo.this,
								"Please select at least one node",
								Toast.LENGTH_SHORT).show();
						return;
					}

				

					/**
					 * 6. Send a file to joined node
					 */
					channel1 = mChordManager.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
					toNode = mNodeListAdapter.getCheckedNodeList().get(0);
					try {
						trId = channel1
								.sendFile(toNode, MESSAGE_TYPE_FILE_NOTIFICATION,
										Path,
										SHARE_FILE_TIMEOUT_MILISECONDS);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					/*
					 * } catch (FileNotFoundException e) { e.printStackTrace(); } //
					 * Set the total count of files to send. (set to 1)
					 */mNodeListAdapter.setFileTotalCnt(toNode, 1, trId);

				//dialog.dismiss();
					
				}
			});
			dialog.show();
			//}
			break;

		default:
			break;
		}
		return true;
	}
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// After selecting files to send
		switch (resultCode) {
		case Activity.RESULT_OK:
			ArrayList<String> fileList = data
					.getStringArrayListExtra("SELECTED_FILE");
			String trId = null;
			String toNode = null;

			SchordChannel channel = mChordManager
					.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);

			for (int i = 0; i < mNodeListAdapter.getCheckedNodeList().size(); i++) {

				// Get the list of checked nodes to send files.
				toNode = mNodeListAdapter.getCheckedNodeList().get(i);

				if (fileList.isEmpty()) {
					Toast.makeText(ShareVideo.this,
							"Please select at least one file.",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (mSend_api == SEND_FILE) {
					if (fileList.size() > 1) {
						Toast.makeText(ShareVideo.this,
								"Don't select more than one file.",
								Toast.LENGTH_SHORT).show();
						return;
					}

					try {

						//*//**
				//		 * 6. Send a file to joined node
				//		 *//*
						trId = channel
								.sendFile(toNode,
										MESSAGE_TYPE_FILE_NOTIFICATION,
										fileList.get(0),
										SHARE_FILE_TIMEOUT_MILISECONDS);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					// Set the total count of files to send. (set to 1)
					mNodeListAdapter.setFileTotalCnt(toNode, 1, trId);

				} else if (mSend_api == SEND_MULTI_FILES) {

					//*//**
				//	 * 6. Send multiFile to joined node
				//	 *//*
					try {
						trId = channel.sendMultiFiles(toNode,
								MESSAGE_TYPE_FILE_NOTIFICATION, fileList,
								SHARE_FILE_TIMEOUT_MILISECONDS);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}

					// Set the total count of files to send.
					mNodeListAdapter.setFileTotalCnt(toNode, fileList.size(),
							trId);
				}

			}

			if (null == trId) { // failed to send
				Toast.makeText(ShareVideo.this,
						getString(R.string.sending_ps_failed, fileList.size()),
						Toast.LENGTH_SHORT).show();
			} else { // succeed to send

				if (mSend_api == SEND_FILE) {
				//	mLogView.appendLog("    sendFile()");

				} else if (mSend_api == SEND_MULTI_FILES) {
					//mLogView.appendLog("    sendMultiFiles() : size "
					//		+ fileList.size());
				}

			}
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		/**
		 * Initialize Chord!
		 */
		if (mChordManager == null) {
			initChord();
		}
	}

	@Override
	public void onDestroy() {
		/**
		 * 8. Release Chord!
		 */
		
		if (mChordManager != null) {
			mChordManager.close();
			mChordManager = null;
		}

		mAlertDialogMap.clear();

		super.onDestroy();
		handler.removeCallbacks(updateprogres);
	}

	private void initChord() {

		/****************************************************
		 * 1. GetInstance
		 ****************************************************/
		Schord chord = new Schord();
		try {
			chord.initialize(ShareVideo.this);
		} catch (SsdkUnsupportedException e) {
			if (e.getType() == SsdkUnsupportedException.VENDOR_NOT_SUPPORTED) {
				// Vender is not SAMSUNG
				return;
			}
		}

		mChordManager = new SchordManager(ShareVideo.this);

		/****************************************************
		 * 2. Set some values before start. It is recommended to use the
		 * application's name and an internal storage of each application as a
		 * directory path. If you want to use secured channel, you should enable
		 * SecureMode. Please refer UseSecureChannelFragment.java
		 * mChordManager.enableSecureMode(true);
		 ****************************************************/
		mChordManager.setLooper(ShareVideo.this.getMainLooper());
		mChordManager.setTempDirectory(chordFilePath);

		/**
		 * Optional. If you need listening network changed, you can set callback
		 * before starting chord.
		 */
		mChordManager.setNetworkListener(new NetworkListener() {

			@Override
			public void onDisconnected(int interfaceType) {
				if (interfaceType == mSelectedInterface) {
					Toast.makeText(
							ShareVideo.this,
							getInterfaceName(interfaceType)
									+ " is disconnected", Toast.LENGTH_SHORT)
							.show();
					mIsStarted = false;
				}
			}

			@Override
			public void onConnected(int interfaceType) {

				// Didn't start yet.
				if ((!mIsStarted) && (mSelectedInterface == -1)) {
					startChord();
				}
			}
		});

		/**
		 * Start Chord!
		 */
		startChord();

	}

	private String getInterfaceName(int interfaceType) {
		if (interfaceType == SchordManager.INTERFACE_TYPE_WIFI) {
			return "Wi-Fi";
		} else if (interfaceType == SchordManager.INTERFACE_TYPE_WIFI_AP) {
			return "Mobile AP";
		} else if (interfaceType == SchordManager.INTERFACE_TYPE_WIFI_P2P) {
			return "Wi-Fi Direct";
		}

		return "UNKNOWN";
	}

	private void startChord() {
		/**
		 * 3. Start Chord using the first interface in the list of available
		 * interfaces. You can get a list of available network interface types
		 * List<Integer> infList =
		 * mChordManager.getAvailableInterfaceTypes().isEmpty();
		 * if(infList.isEmpty()) // there is no active interface!
		 */
		List<Integer> infList = mChordManager.getAvailableInterfaceTypes();
		if (infList.isEmpty()) {
			//mLogView.appendLog("    There is no available connection.");
			return;
		}

		mSelectedInterface = infList.get(0);

		try {

			mChordManager.start(mSelectedInterface, mManagerListener);
		//	mLogView.appendLog("    start("
		//			+ getInterfaceName(mSelectedInterface) + ")");
		} catch (IllegalArgumentException e) {
		//	mLogView.appendLog("    Fail to start -" + e.getMessage());
		} catch (InvalidInterfaceException e) {
		//	mLogView.appendLog("    There is no such a connection.");
		} catch (Exception e) {
		//	mLogView.appendLog("    Fail to start -" + e.getMessage());
		}

	}

	/**
	 * ChordManagerListener
	 */
	private SchordManager.StatusListener mManagerListener = new SchordManager.StatusListener() {

		/**
		 * 4. Chord has started successfully
		 */
		@Override
		public void onStarted(String nodeName, int reason) {

		//	mMyNodeName_textView.setText(mChordManager.getName());
			mIsStarted = true;

			if (reason == STARTED_BY_USER) {
				// Success to start by calling start() method
			//	mLogView.appendLog("    >onStarted(STARTED_BY_USER)");
				joinTestChannel();
			} else if (reason == STARTED_BY_RECONNECTION) {
				// Re-start by network re-connection.
				//mLogView.appendLog("    >onStarted(STARTED_BY_RECONNECTION)");
			}
		}

		/**
		 * 9. Chord has stopped successfully
		 */
		@Override
		public void onStopped(int reason) {
			if (NETWORK_DISCONNECTED == reason) {
				// Stopped by network disconnected
				//mLogView.appendLog("    >onStopped(NETWORK_DISCONNECTED)");
				mNodeListAdapter.removeNodeAll();
			}
		}

	};

	private void joinTestChannel() {
		SchordChannel channel = null;

		/**
		 * 5. Join my channel
		 */
		channel = mChordManager.joinChannel(CHORD_SEND_TEST_CHANNEL,
				mChannelListener);

		if (channel == null) {
			//mLogView.appendLog("    Fail to joinChannel");
		}
	}

	// ***************************************************
	// ChordChannelListener
	// ***************************************************
	private SchordChannel.StatusListener mChannelListener = new SchordChannel.StatusListener() {

		/**
		 * Called when a node leave event is raised on the channel.
		 */
		@Override
		public void onNodeLeft(String fromNode, String fromChannel) {
			//mLogView.appendLog("    >onNodeLeft() : " + fromNode);
			mNodeListAdapter.removeNode(fromNode);
			
			Toast.makeText(getBaseContext(), ""+fromNode+" has left", Toast.LENGTH_SHORT).show();
			if (mNodeListAdapter.isEmpty()) {
				isshared=false;
			}

		}

		/**
		 * Called when a node join event is raised on the channel.
		 */
		@Override
		public void onNodeJoined(String fromNode, String fromChannel) {
		//	mLogView.appendLog("    >onNodeJoined() : " + fromNode);
			mNodeListAdapter.addNode(fromNode);

		}

		/**
		 * Called when the Share file notification is received. User can decide
		 * to receive or reject the file.
		 */
		@Override
		public void onMultiFilesWillReceive(String fromNode,
				String fromChannel, String fileName, String taskId,
				int totalCount, String fileType, long fileSize) {

			//mLogView.appendLog("    >onMultiFilesWillReceive()\n     : "
		//			+ taskId + " " + totalCount);
			if (checkAvailableMemory(fileSize)) {
				displayFileNotify(
						fromNode,
						getString(R.string.file_ps_total_pd, fileName,
								totalCount), taskId, SEND_MULTI_FILES);

				// Set the total count of files to receive.
				mNodeListAdapter.setFileTotalCnt(fromNode, totalCount, taskId);
			} else {
				// Because the external storage may be unavailable,
				// you should verify that the volume is available before
				// accessing it.
				// But also, onMultiFilesFailed with ERROR_FILE_SEND_FAILED will
				// be called while Chord got failed to write file.
				SchordChannel channel = mChordManager
						.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
				channel.rejectMultiFiles(taskId);
			//	mLogView.appendLog("    >onMultiFilesWillReceive()\n     : There is not enough storage available. Reject receiving.");
			}

		}

		/**
		 * Called when the sending a file is completed.
		 */
		@Override
		public void onMultiFilesSent(String toNode, String toChannel,
				String fileName, String taskId, int index, String fileType) {

		//	mLogView.appendLog("    >onMultiFilesSent()\n     : " + taskId
			//		+ " " + index);

			// Remove the progressBar that completed sending files.
			mNodeListAdapter.removeProgress(index, taskId);
		}

		/**
		 * Called when the receiving a file is completed from the node.
		 */
		@Override
		public void onMultiFilesReceived(String fromNode, String fromChannel,
				String fileName, String taskId, int index, String fileType,
				long fileSize, String tmpFilePath) {

			//mLogView.appendLog("    >onMultiFilesReceived()\n     : " + taskId
			//		+ " " + index);

			// Remove the progressBar that completed receiving files.
			mNodeListAdapter.removeProgress(index, taskId);

			saveFile(fileName, tmpFilePath);
		}

		/**
		 * Called when the file transfer is finished to the node.
		 */
		@Override
		public void onMultiFilesFinished(String node, String channel,
				String taskId, int reason) {

			switch (reason) {
			case ERROR_FILE_REJECTED: {
				//mLogView.appendLog("    >onMultiFilesFinished()\n     : REJECTED - "
				//		+ taskId);
				break;
			}
			case ERROR_FILE_CANCELED: {
				//mLogView.appendLog("    >onMultiFilesFinished()\n     : CANCELED - "
				//		+ taskId);
				break;
			}
			case ERROR_NONE:
				//mLogView.appendLog("    >onMultiFilesFinished()");
				//break;
			default:
				//mLogView.appendLog("    >onMultiFilesFinished()\n     : Error["
				//		+ reason + "] - " + taskId);
				break;
			}

		}

		/**
		 * Called when the error is occurred while the file transfer is in
		 * progress.
		 **/
		@Override
		public void onMultiFilesFailed(String node, String channel,
				String fileName, String taskId, int index, int reason) {
			switch (reason) {
			case ERROR_FILE_REJECTED: {
			//	mLogView.appendLog("    >onMultiFilesFailed()\n     : REJECTED - "
			//			+ taskId + " " + index);
				break;
			}

			case ERROR_FILE_CANCELED: {
				//mLogView.appendLog("    >onMultiFilesFailed()\n     : CANCELED - "
				//		+ taskId + " " + index);
				break;
			}

			case ERROR_FILE_TIMEOUT: {
				//mLogView.appendLog("    >onMultiFilesFailed()\n     : TIME OUT - "
				//		+ fileName);
				break;

			}
			default:
			//	mLogView.appendLog("    >onMultiFilesFailed()\n     : Error["
					//	+ reason + "] - " + taskId + " " + index);
				break;
			}

			mNodeListAdapter.removeProgress(index, taskId);
			AlertDialog alertDialog = mAlertDialogMap.get(taskId);
			if (alertDialog != null) {
				alertDialog.dismiss();
				mAlertDialogMap.remove(taskId);
			}
		}

		/**
		 * Called when an individual chunk of the file is sent.
		 */
		@Override
		public void onMultiFilesChunkSent(String toNode, String toChannel,
				String fileName, String taskId, int index, String fileType,
				long fileSize, long offset, long chunkSize) {

			// Set the progressBar - add or update
			int progress = (int) (100 * offset / fileSize);
			mNodeListAdapter.setProgressUpdate(toNode, taskId, index, progress,
					true, true);
			expandeGroup();
		}

		/**
		 * Called when the receiving a file is completed from the node.
		 */
		@Override
		public void onMultiFilesChunkReceived(String fromNode,
				String fromChannel, String fileName, String taskId, int index,
				String fileType, long fileSize, long offset) {

			// Set the progressBar - add or update
			int progress = (int) (100 * offset / fileSize);
			mNodeListAdapter.setProgressUpdate(fromNode, taskId, index,
					progress, true, false);
			expandeGroup();
		}

		/**
		 * Called when the Share file notification is received. User can decide
		 * to receive or reject the file.
		 */
		@Override
		public void onFileWillReceive(String fromNode, String fromChannel,
				String fileName, String hash, String fileType,
				String exchangeId, long fileSize) {

			//mLogView.appendLog("    >onFileWillReceive()\n     : " + fileName);
			if (checkAvailableMemory(fileSize)) {
				displayFileNotify(fromNode, fileName, exchangeId, SEND_FILE);
				// Set the total count of files to receive.
				mNodeListAdapter.setFileTotalCnt(fromNode, 1, exchangeId);
			} else {
				// Because the external storage may be unavailable,
				// you should verify that the volume is available before
				// accessing it.
				// But also, onFileFailed with ERROR_FILE_SEND_FAILED will be
				// called while Chord got failed to write file.
				SchordChannel channel = mChordManager
						.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
				channel.rejectFile(exchangeId);
				//mLogView.appendLog("    >onFileWillReceive()\n     : There is not enough storage available. Reject receiving.");
			}

		}

		/**
		 * Called when the file transfer is completed to the node.
		 */
		@Override
		public void onFileSent(String toNode, String toChannel,
				String fileName, String hash, String fileType, String exchangeId) {

		//	mLogView.appendLog("    >onFileSent()\n     : "
		//			+ new File(fileName).getName());
			mNodeListAdapter.removeProgress(1, exchangeId);
			videoView.getCurrentPosition();

			 byte[][] payload = new byte[1][];
	            payload[0] = (""+videoView.getCurrentPosition()).getBytes();
			toNode = mNodeListAdapter.getCheckedNodeList().get(0);
			SchordChannel channel = mChordManager.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);
           channel.sendData(toNode, "startvideo", payload);
           isshared=true;
           Toast.makeText(getBaseContext(), "Finished sending !", Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			
			
		}

		/**
		 * Called when the file transfer is completed from the node.
		 */
		@Override
		public void onFileReceived(String fromNode, String fromChannel,
				String fileName, String hash, String fileType,
				String exchangeId, long fileSize, String tmpFilePath) {

		//	mLogView.appendLog("    >onFileReceived()\n     : " + fileName);
			mNodeListAdapter.removeProgress(1, exchangeId);

			saveFile(fileName, tmpFilePath);
			viewcontrolplayer.setVisibility(View.GONE);
			isshared=true;
		//	dialog.dismiss();
		}

		/**
		 * Called when the error is occurred while the file transfer is in
		 * progress.
		 **/
		@Override
		public void onFileFailed(String node, String channel, String fileName,
				String hash, String exchangeId, int reason) {

			switch (reason) {
			case ERROR_FILE_REJECTED: {
			//	mLogView.appendLog("    >onFileFailed()\n     : REJECTED - "
			//			+ fileName);
				break;
			}
			case ERROR_FILE_CANCELED: {
				//mLogView.appendLog("    >onFileFailed()\n     : CANCELED - "
				//		+ fileName);
				break;
			}
			case ERROR_FILE_TIMEOUT: {
			//	mLogView.appendLog("    >onFileFailed()\n     : TIME OUT - "
				//		+ fileName);
				break;

			}
			default:
				//mLogView.appendLog("    >onFileFailed()\n     : Error["
				//		+ reason + "] - " + node);
				break;
			}

			mNodeListAdapter.removeProgress(1, exchangeId);

			AlertDialog alertDialog = mAlertDialogMap.get(exchangeId);
			if (alertDialog != null) {
				alertDialog.dismiss();
				mAlertDialogMap.remove(exchangeId);
			}
		}

		/**
		 * Called when an individual chunk of the file is sent.
		 */
		@Override
		public void onFileChunkSent(String toNode, String toChannel,
				String fileName, String hash, String fileType,
				String exchangeId, long fileSize, long offset, long chunkSize) {

			// Set the progressBar - add or update
			int progress = (int) (100 * offset / fileSize);
			mNodeListAdapter.setProgressUpdate(toNode, exchangeId, 1, progress,
					false, true);
			
			
			
		    
		    
		    
			expandeGroup();
		}

		/**
		 * Called when the file transfer is completed from the node.
		 */
		@Override
		public void onFileChunkReceived(String fromNode, String fromChannel,
				String fileName, String hash, String fileType,
				String exchangeId, long fileSize, long offset) {
			// Set the progressBar - add or update
			int progress = (int) (100 * offset / fileSize);
			mNodeListAdapter.setProgressUpdate(fromNode, exchangeId, 1,
					progress, false, false);
			
			
		
		    
		    
			expandeGroup();
		}

		/**
		 * The following callBack is not used in this Fragment. Please refer to
		 * the HelloChordFragment.java
		 */
		@Override
		public void onDataReceived(String fromNode, String fromChannel,
				String payloadType, byte[][] payload) {
			if(payloadType.equals("playpause")){
               // mLogView.appendLog("    >onDataReceived(" + fromNode + ", " + new String( payload[0]) + ")");
				if ((new String(payload[0])+"").equals("play")) {
					videoView.start();
				}else{videoView.pause();}
				
            }
			
			
			if(payloadType.equals("currentpositionpg")){
	               // mLogView.appendLog("    >onDataReceived(" + fromNode + ", " + new String( payload[0]) + ")");
					videoView.seekTo(Integer.parseInt(new String(payload[0])+""));
					updateProgressBar1();
	            }
			
			if(payloadType.equals("startvideo")){
	               // mLogView.appendLog("    >onDataReceived(" + fromNode + ", " + new String( payload[0]) + ")");
					videoView.seekTo(Integer.parseInt(new String(payload[0])+"")+1000);
				
					updateProgressBar1();
	            }
		
		
		
			if(payloadType.equals("nodeout")){
	               // mLogView.appendLog("    >onDataReceived(" + fromNode + ", " + new String( payload[0]) + ")");
					isshared=false;
					Toast.makeText(getBaseContext(), ""+ new String(payload[0])+ " has left", Toast.LENGTH_SHORT).show();
	            }
		
		}
	};

	private boolean checkAvailableMemory(long fileSize) {
		File targetdir = new File(chordFilePath);
		if (!targetdir.exists()) {
			targetdir.mkdirs();
		}

		StatFs stat = new StatFs(chordFilePath);
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getAvailableBlocks();
		long availableMemory = blockSize * totalBlocks;

		if (availableMemory < fileSize) {
			return false;
		}
		
		

		return true;
	}

	private void displayFileNotify(final String nodeName,
			final String fileName, final String trId, final int sendApi) {

		// for dialog whether accept the file transfer or not.
		AlertDialog alertDialog = new AlertDialog.Builder(ShareVideo.this)
				.setTitle("Receive Files")
				.setMessage(
						getString(R.string.from_ps_file_ps, nodeName, fileName))
				.setPositiveButton(R.string.accept,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								/**
								 * 6. Accept the file transfer
								 */

								if (senderLeft(nodeName)
										|| !mAlertDialogMap.containsKey(trId)) {
									return;
								}

								SchordChannel channel = mChordManager
										.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);

								if (sendApi == SEND_FILE) {

									channel.acceptFile(trId, 30 * 1000, 2,
											300 * 1024);
									//mLogView.appendLog("    acceptFile()");

								} else if (sendApi == SEND_MULTI_FILES) {

									channel.acceptMultiFiles(trId, 30 * 1000,
											2, 300 * 1024);
								//	mLogView.appendLog("    acceptMultiFiles()");

								}

								mAlertDialogMap.remove(trId);

							}
						})
				.setNegativeButton(R.string.reject,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								/**
								 * 6. Reject the file transfer
								 */

								if (senderLeft(nodeName)
										|| !mAlertDialogMap.containsKey(trId)) {
									return;
								}

								SchordChannel channel = mChordManager
										.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);

								if (sendApi == SEND_FILE) {

									channel.rejectFile(trId);
									//mLogView.appendLog("    rejectFile()");

								} else if (sendApi == SEND_MULTI_FILES) {

									channel.rejectMultiFiles(trId);
								//	mLogView.appendLog("    rejectMultiFiles()");

								}

								mAlertDialogMap.remove(trId);

							}
						}).create();

		alertDialog.show();

		mAlertDialogMap.put(trId, alertDialog);
	}

	private boolean senderLeft(String nodeName) {
		for (String sender : mNodeListAdapter.getNodeList()) {
			if (sender.equals(nodeName)) {
				return false;
			}
		}
	//	mLogView.appendLog("    The sender left.");

		return true;
	}

	private void saveFile(String fileName, String tmpFilePath) {
		// Save received files.

		String savedName = fileName;
		String name, ext;

		int i = savedName.lastIndexOf(".");
		if (i == -1) {
			name = savedName;
			ext = "";
		} else {
			name = savedName.substring(0, i);
			ext = savedName.substring(i);
		}

		 targetFile = new File(chordFilePath, savedName);
		int index = 0;
		while (targetFile.exists()) {
			savedName = name + "_" + index + ext;
			targetFile = new File(chordFilePath, savedName);
			index++;
		}

		File srcFile = new File(tmpFilePath);
		srcFile.renameTo(targetFile);

		Toast.makeText(getBaseContext(), targetFile+"", Toast.LENGTH_SHORT).show();
		videoView.setVideoPath(""+targetFile);
	     
      videoView.requestFocus();
       videoView.start();
       videoView.setOnCompletionListener(new OnCompletionListener() {
		
		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub
			videoView.setVideoPath(""+targetFile);	
			videoView.start();
			seckbarprogress.setMax(100);
			updateProgressBar1();}
	});
	}

	private void expandeGroup() {
		// Expand the list of the progressBar

		int nodeCnt = mNodeListAdapter.getGroupCount();
	//	Toast.makeText(getBaseContext(), nodeCnt+"", Toast.LENGTH_SHORT).show();
		for (int i = 0; i < nodeCnt; i++) {
		//	mNode_listView.expandGroup(i);
		}
	}

	// **********************************************************************
	// From adapter
	// **********************************************************************
	@Override
	public void onFileCanceled(String node, String trId, int index,
			boolean bMulti) {

		// Get the joined channel to call the cancel API
		SchordChannel channel = mChordManager
				.getJoinedChannel(CHORD_SEND_TEST_CHANNEL);

		if (bMulti) {
			/**
			 * 7. Cancel the multiFile transfer
			 */
			channel.cancelMultiFiles(trId);
			//mLogView.appendLog("    cancelMultiFiles()");
			mNodeListAdapter.removeCanceledProgress(node, trId);

		} else {
			/**
			 * 7. Cancel the file transfer
			 */
			channel.cancelFile(trId);
			//mLogView.appendLog("    cancelFile()");
			mNodeListAdapter.removeProgress(index, trId);
		}
	}

	private static final String CHORD_SEND_TEST_CHANNEL = "com.samsung.android.sdk.chord.example.SENDTESTCHANNEL";

	private static final String MESSAGE_TYPE_FILE_NOTIFICATION = "FILE_NOTIFICATION_V2";

	private static final String chordFilePath = Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/ChordExample";

	private static final int SHARE_FILE_TIMEOUT_MILISECONDS = 1000 * 60 * 60;

	private static final int SEND_FILE = 1;

	private static final int SEND_MULTI_FILES = 2;

	private int mSend_api = 2;

	private TextView mMyNodeName_textView;

	private ExpandableListView mNode_listView;

	private NodeListAdapter mNodeListAdapter = null;

	private Button mSend_btn;

	private Spinner mSend_version_spinner;

	private Spinner mMultifiles_limitCnt_spinner;

	private int mMultfiles_limitCnt = 1;

	

	private SchordManager mChordManager = null;

	private ArrayList<String> nodeEventLogArray = new ArrayList<String>();

	private HashMap<String, AlertDialog> mAlertDialogMap = null;

	private boolean mIsStarted = false;

	private int mSelectedInterface = -1;
	File targetFile;
}
